package com.example.myapplication.activity;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myapplication.R;

import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceManager;

import com.example.myapplication.bean.User;
import com.example.myapplication.R;
import com.example.myapplication.utils.CodeUtils;
import com.example.myapplication.utils.SharedPreferencesUtil;
import com.example.myapplication.utils.StoreUI;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;

import android.content.SharedPreferences;
import okhttp3.Call;
import okhttp3.OkHttpClient;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import androidx.appcompat.app.AppCompatDelegate;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import org.json.JSONArray;
import org.json.JSONObject;

public class activity_info extends AppCompatActivity {

    private TextView tv_mian_bar;
    private Button tv_back;
    private Button sub;
    private ListView t_info;
    private EditText e_com;
    private ImageView pic;
    private String img,storename,type,username,comment;//location和type补充

    private String picture = "";
    private List<StoreUI> list = new ArrayList<>();
    // 创建数据列表
    private List<String> data = new ArrayList<>();

    //Glide请求图片选项配置
    /*private RequestOptions requestOptions = RequestOptions
            .diskCacheStrategy(DiskCacheStrategy.NONE)//不做磁盘缓存
            .skipMemoryCache(true);//不做内存缓存*/

    RequestOptions requestOptions = new RequestOptions()
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .fitCenter();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_info);
        //去除默认标题栏
        ActionBar actionBar=getSupportActionBar();
        if(actionBar!=null){
            actionBar.hide();
        }
        init();
    }

    private  void init(){
        pic=(ImageView)findViewById(R.id.imageView_info);
        tv_mian_bar = (TextView) findViewById(R.id.tv_main_title);
        tv_mian_bar.setText("Info");
        t_info=(ListView)findViewById(R.id.listview_info);
        t_info.setTranscriptMode(ListView.TRANSCRIPT_MODE_DISABLED);
        //获取storename
        Intent intent = getIntent();
        storename = intent.getStringExtra("storename");

        tv_back = (Button) findViewById(R.id.tv_back);

        //返回按钮监听
        tv_back.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                activity_info.this.finish();
            }
        });

        //获取userid
        SharedPreferences sp=getSharedPreferences("loginInfo", MODE_PRIVATE);
        //SharedPreferences.Editor editor=sp.edit();//获取编辑器
        username=sp.getString("loginUserName","default");

        //获取当前时间
        SimpleDateFormat   formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate =  new Date(System.currentTimeMillis());
        //获取当前时间
        String  time =  formatter.format(curDate);

//        t_info.setText("用户名："+username+"\n商家名："+storename+"\n评论");

        /*HttpUtil.sendRequestWithOkhttp("http://121.36.92.128:8086/getComments", new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                parseJsonWithJsonObject(response);

            }
        });*/
//图片接口等待实现
        //返回信息
        final int[] count = {0};     //计数
        CountDownTimer timer = new CountDownTimer(1000000000,2000) {
            int firstVisibleItem;
            int yOffset;
            @Override
            public void onTick(long l) {

                // 记录当前的第一个可见项的索引和偏移量
                firstVisibleItem = t_info.getFirstVisiblePosition();
                View firstVisibleView = t_info.getChildAt(0);
                yOffset = (firstVisibleView != null) ? firstVisibleView.getTop() : 0;

                OkHttpUtils
                        .get()
                        .url("http://121.36.92.128:8086//storeUI")
                        .addParams("storename", storename)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                System.out.println(e.toString());
                            }

                            @Override
                            public void onResponse(String response, int id) {

                                if (!response.equals("[]")) {
                                    try {
                                        int jud_type = 0,jud_picture = 0;
                                        JSONArray jsonArray = new JSONArray(response);
                                        if(data.size() != 0)
                                            data.clear();
                                        for(int i = 0; i < jsonArray.length();i++)
                                        {
                                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                                            data.add("\n"+jsonObject.getString("userid")+": "+jsonObject.getString("comment")+"\n"+jsonObject.getString("time"));
                                            if(picture.isEmpty())
                                                picture = jsonObject.getString("picture");
                                        }
                                        // 在更新 ListView 数据之前，将适配器设置为 null
                                        t_info.setAdapter(null);
                                        ArrayAdapter<String> adapter = new ArrayAdapter<>(activity_info.this, android.R.layout.simple_list_item_1, data);
                                        t_info.setAdapter(adapter);
                                        // 使用保存的索引和偏移量将 ListView 滚动到之前的位置
                                        t_info.setSelectionFromTop(firstVisibleItem, yOffset);
                                       // t_info.smoothScrollToPosition(adapter.getCount() - 1);
                                        if(!picture.isEmpty()){
                                            Glide.with(activity_info.this).load(picture).apply(requestOptions).into(pic);
                                        }
                                    }catch(Exception e){
                                        System.out.println(e);
                                    }
                                }  else if(count[0] == 0){
                                    Toast.makeText(activity_info.this, "暂无评论", Toast.LENGTH_SHORT).show();
                                    count[0]++;
                                }
                            }
                        });
            }

            @Override
            public void onFinish() {

            }
        }.start();

//        OkHttpUtils
//                .get()
//                .url("http://121.36.92.128:8086/searchByName")
//                .addParams("storename", storename)
//                .build()
//                .execute(new StringCallback() {
//                    @Override
//                    public void onError(Call call, Exception e, int id) {
//                        System.out.println(e.toString());
//                    }
//
//                    @Override
//                    public void onResponse(String response, int id) {
//
//                        if (!response.equals("[]")) {
//                            Gson gson = new Gson();
//                            JsonArray jsonArray = gson.fromJson(response, JsonArray.class);
//
//// 假设只有一个对象，获取第一个对象
//                            JsonObject jsonObject = jsonArray.get(0).getAsJsonObject();
//
//                            type = jsonObject.get("type").getAsString();
////                            img=jsonObject.get("picture").getAsString();
//                            type = response;
//
//                        }  else {
//                            Toast.makeText(activity_info.this, "加载失败", Toast.LENGTH_SHORT).show();
//                        }
//                    }
//                });
////添加历史记录
        OkHttpUtils
                .post()
                .url("http://121.36.92.128:8086/addHistory")
                .addParams("userid",username)
                .addParams("storename", storename)
                .addParams("time",time)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        System.out.println(e.toString());
                    }

                    @Override
                    public void onResponse(String response, int id) {

                        if (response.equals("true")) {
                            System.out.println("添加历史记录成功");

                        }  else {
                            System.out.println("添加历史记录失败");
                        }
                    }
                });



// 使用 Glide 加载图片
        /*RequestOptions options = new RequestOptions()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .fitCenter();// 根据需要进行缓存策略配置

        Glide.with(this)
                .load(img)//url链接
                .apply(options)
                .into(pic);*/
        //显示相关信息




        //提交评论按钮
        sub = (Button) findViewById(R.id.button_smt);
        e_com=(EditText)findViewById(R.id.edit_comment);
        //提交评论按钮监听
        sub.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                comment=e_com.getText().toString().trim();
                //提交comment
                if (TextUtils.isEmpty(comment)) {
                    Toast.makeText(activity_info.this, "请输入评价", Toast.LENGTH_SHORT).show();
                } else{
                    OkHttpUtils
                            .post()
                            .url("http://121.36.92.128:8086/addComment")
                            .addParams("storename",storename)
                            .addParams("comments", comment)
                            .addParams("userid",username)
                            .addParams("time_com",time)
                            .build()
                            .execute(new StringCallback() {
                                @Override
                                public void onError(Call call, Exception e, int i) {
                                    System.out.println(e.toString());
                                }

                                @Override
                                public void onResponse(String response, int i) {
                                    if (response.equals("true")) {
                                        Toast.makeText(activity_info.this, "评价成功", Toast.LENGTH_SHORT).show();
                                        return;
                                    }  else {
                                        Toast.makeText(activity_info.this, "评价失败", Toast.LENGTH_SHORT).show();
                                    }
                                }


                            });
                }
            }
        });
    }
}